﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using DevExpress.XtraEditors;
using DevExpress.XtraBars;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using System.Data.SqlClient;
using System.Data;
using DevExpress.XtraReports.UI;
using System.IO;
using DevExpress.XtraReports.UserDesigner;
using DevExpress.XtraTabbedMdi;
using DevExpress.Utils;
using System.ComponentModel.Design;
using DevExpress.XtraReports.Parameters;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrinting.Preview;

namespace SAF.Controls
{
    public class ReportManager
    {
        private System.ComponentModel.IContainer components = null;

        private BarButtonItem previewItem = null;
        private BarButtonItem printItem = null;
        private BarButtonItem pageSetupItem = null;
        private BarButtonItem editItem = null;
        private BarButtonItem newItem = null;
        private bool IsNewReport = false;
        private BarManager m_BarManager = null;
        private PopupMenu m_PopupMenu = null;

        private Guid m_ReportGuid = Guid.Empty;
        private DropDownButton m_DropDownButton = null;
        private BarSubItem m_BarSubItem = null;

        private string m_ConnectionString = string.Empty;
        private XRDesignRibbonForm m_ReportDesignerForm = null;
        private bool reportChanged = false;
        private sysReport aLastAddFormat = null;
        private sysReport currReportFormat = null;
        private List<Parameter> reportRarameters;

        private List<sysReport> sysReports = new List<sysReport>();

        /// <summary>
        /// 用户自定义数据源
        /// </summary>
        public event EventHandler<ReportManagerCustomDataSourceEventArgs> CustomDataSource;

        private BarManager Manager
        {
            get
            {
                if (this.m_BarSubItem != null)
                {
                    return m_BarSubItem.Manager;
                }
                else
                {
                    return CreateBarManager();
                }
            }
        }

        private BarManager CreateBarManager()
        {
            if (m_BarManager == null)
            {
                m_BarManager = new BarManager(this.components);
                m_BarManager.Form = this.m_DropDownButton.TopLevelControl;
                this.m_DropDownButton.MenuManager = m_BarManager;
            }
            return m_BarManager;
        }

        /// <summary>
        /// 下拉菜单
        /// </summary>
        private PopupMenu PopupMenu
        {
            get
            {
                if (m_PopupMenu == null)
                {
                    m_PopupMenu = new PopupMenu(this.components);
                    m_PopupMenu.Manager = this.Manager;
                }
                return m_PopupMenu;
            }
        }
        /// <summary>
        /// 初始化下拉菜单
        /// </summary>
        private void InitPopupMenu()
        {
            if (Manager == null)
            {
                throw new NullReferenceException("ReportManager的BarManager为空。");
            }
            Manager.BeginInit();
            try
            {
                if (this.m_DropDownButton != null)
                {
                    PopupMenu.LinksPersistInfo.Clear();
                }
                if (this.m_BarSubItem != null)
                {
                    this.m_BarSubItem.LinksPersistInfo.Clear();
                }
                //预览
                previewItem = new BarButtonItem(Manager, "预览");
                previewItem.Glyph = Properties.Resources.Action_Preview;
                previewItem.ItemClick += new ItemClickEventHandler(item_ItemClick);

                //打印
                printItem = new BarButtonItem(Manager, "打印");
                printItem.Glyph = Properties.Resources.Action_Print;
                printItem.ItemClick += new ItemClickEventHandler(item_ItemClick);
                //页面设置
                pageSetupItem = new BarButtonItem(Manager, "页面设置");
                pageSetupItem.Glyph = Properties.Resources.Action_PageSetup;
                pageSetupItem.ItemClick += new ItemClickEventHandler(item_ItemClick);

                var links = new LinkPersistInfo[] { new LinkPersistInfo(previewItem), new LinkPersistInfo(printItem), new LinkPersistInfo(pageSetupItem, true) };
                //添加到DropDownButton
                if (this.m_DropDownButton != null)
                {
                    this.PopupMenu.LinksPersistInfo.AddRange(links);
                }
                //添加到BarSubItem
                if (this.m_BarSubItem != null)
                {
                    this.m_BarSubItem.LinksPersistInfo.AddRange(links);
                }

                this.GetReports();

                if (sysReports.Where(p => p.IsDefault == true).Count() <= 0 && sysReports.Count > 0)
                {
                    sysReports[0].IsDefault = true;
                }

                //设计报表
                editItem = new BarButtonItem(Manager, "设计报表");
                editItem.Glyph = Properties.Resources.Action_Report_ShowDesigner;
                editItem.ItemClick += new ItemClickEventHandler(item_ItemClick);
                //新建报表
                newItem = new BarButtonItem(Manager, "新建报表");
                newItem.Glyph = Properties.Resources.Action_New;
                newItem.ItemClick += new ItemClickEventHandler(item_ItemClick);

                links = new LinkPersistInfo[] { new LinkPersistInfo(editItem, true), new LinkPersistInfo(newItem) };

                if (this.m_DropDownButton != null)
                {
                    this.PopupMenu.LinksPersistInfo.AddRange(links);
                    this.m_DropDownButton.DropDownControl = PopupMenu;
                    this.m_DropDownButton.Click += new EventHandler(m_DropDownButton_Click);
                }

                if (this.m_BarSubItem != null)
                {
                    this.m_BarSubItem.LinksPersistInfo.AddRange(links);
                }

                //添加报表项
                for (int i = 0; i < sysReports.Count; i++)
                {
                    BarCheckItem barCheckItem = new BarCheckItem(Manager, sysReports[i].IsDefault ? true : false);
                    if (sysReports[i].IsDefault)
                    {
                        currReportFormat = sysReports[i];
                    }
                    barCheckItem.Caption = sysReports[i].ReportFormatName;
                    barCheckItem.Tag = sysReports[i];
                    barCheckItem.ItemClick += new ItemClickEventHandler(barCheckItem_ItemClick);

                    if (this.m_DropDownButton != null)
                    {
                        this.PopupMenu.LinksPersistInfo.Add(new LinkPersistInfo(barCheckItem, i == 0 ? true : false));
                    }
                    if (this.m_BarSubItem != null)
                    {
                        this.m_BarSubItem.LinksPersistInfo.Add(new LinkPersistInfo(barCheckItem, i == 0 ? true : false));
                    }
                }

            }
            finally
            {
                if (Manager != null)
                    Manager.EndInit();
            }
        }

        private void GetReports()
        {
            try
            {
                using (SqlConnection con = new SqlConnection(this.m_ConnectionString))
                {
                    var cmd = con.CreateCommand();
                    SqlDataReader reader = null;
                    try
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "select Iden, ReportGuid, ReportFormatName, IsDefault, SortIndex, IsActive, Remark from SysReport with(nolock) where ReportGuid=@ReportGuid order by SortIndex,ReportFormatName";
                        SqlParameter param = new SqlParameter("@ReportGuid", SqlDbType.UniqueIdentifier);
                        param.Value = this.m_ReportGuid;
                        cmd.Parameters.Add(param);
                        con.Open();
                        reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                sysReports.Add(new sysReport(reader));
                            }
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        if (reader != null)
                            reader.Dispose();
                    }
                }
            }
            catch
            {
                throw;
            }
        }

        private byte[] GetReportFormat(Guid reportFormatIden)
        {
            string sql = "SELECT TOP 1 ReportFormat FROM dbo.SysReport WITH(NOLOCK) WHERE Iden=@Iden";
            using (SqlConnection con = new SqlConnection(this.m_ConnectionString))
            {
                var cmd = con.CreateCommand();
                SqlDataReader reader = null;
                try
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    SqlParameter param = new SqlParameter("@Iden", SqlDbType.UniqueIdentifier);
                    param.Value = reportFormatIden;
                    cmd.Parameters.Add(param);
                    con.Open();
                    reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (reader.HasRows)
                    {
                        if (reader.Read())
                        {
                            return reader["ReportFormat"] as byte[];
                        }
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    if (reader != null)
                        reader.Dispose();
                }
            }
            return null;
        }

        private XtraReport CreateReport(byte[] bytes, bool loadState)
        {
            XtraReport report = null;
            //如果报表数据为空，返回新报表数据,比如编辑数据为空时应该新创建报表
            if (bytes == null || bytes.Length < 1)
            {
                report = new XtraReport();
            }
            else
            {
                report = XtraReport.FromStream(new MemoryStream(bytes), loadState);
            }
            report.DataSource = GetReportDataSource();
            SetReportParameter(report);
            return report;
        }

        private object GetReportDataSource()
        {
            ReportManagerCustomDataSourceEventArgs reportManagerDataSourceEventArgs = new ReportManagerCustomDataSourceEventArgs()
            {
                ReportGuid = this.m_ReportGuid,
                ReportFormatName = currReportFormat == null ? aLastAddFormat.ReportFormatName : currReportFormat.ReportFormatName
            };
            OnCustomDataSource(reportManagerDataSourceEventArgs);
            return reportManagerDataSourceEventArgs.DataSource;
        }

        private void OnCustomDataSource(ReportManagerCustomDataSourceEventArgs e)
        {
            if (CustomDataSource != null)
                CustomDataSource(this, e);
        }

        void m_DropDownButton_Click(object sender, EventArgs e)
        {
            this.m_DropDownButton.ShowDropDown();
        }

        private void barCheckItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            BarCheckItem checkedItem = (BarCheckItem)e.Item;
            if (checkedItem.Checked)
            {
                UnCheckPopupMenuCheckItem();
                checkedItem.Checked = true;
            }
            currReportFormat = (sysReport)checkedItem.Tag;
        }

        private void item_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.Item == previewItem)
            {
                ShowPreviewReportFormatDialog();
            }
            else if (e.Item == newItem)
            {
                ShowNewReportFormatDesigner();
            }
            else if (e.Item == pageSetupItem)
            {
                ShowPrintPageSetupDialog();
            }
            else if (e.Item == editItem)
            {
                ShowEditReportForamtDesigner();
            }
            else if (e.Item == printItem)
            {
                ShowPrintReportFormatDialog();
            }
        }
        /// <summary>
        /// 预览报表
        /// </summary>
        public void ShowPreviewReportFormatDialog()
        {
            var report = GetDefaultReport();
            if (report != null)
            {
                PrintPreviewRibbonFormEx PreviewRibbonForm = new PrintPreviewRibbonFormEx();
                PreviewRibbonForm.Text = report.DisplayName + " - Preview";
                PreviewRibbonForm.PrintingSystem = report.PrintingSystem;
                PreviewRibbonForm.PrintingSystem.SetCommandVisibility(PrintingSystemCommand.Save, DevExpress.XtraPrinting.CommandVisibility.None);
                PreviewRibbonForm.PrintingSystem.SetCommandVisibility(PrintingSystemCommand.Open, DevExpress.XtraPrinting.CommandVisibility.None);
                var pageGroup = PreviewRibbonForm.RibbonControl.GetGroupByName("Document");
                if (pageGroup != null)
                {
                    pageGroup.Visible = false;
                }
                //TODO:预览时数字的DisplayName会有问题
                report.CreateDocument(true);
                PreviewRibbonForm.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("当前没有选中的报表，无法预览！", "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 页面设置
        /// </summary>
        public void ShowPrintPageSetupDialog()
        {
            var report = GetDefaultReport();
            if (report != null)
            {
                report.ShowPageSetupDialog();
            }
            else
            {
                XtraMessageBox.Show("当前没有选中的报表，无法设置报表格式！", "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 打印报表
        /// </summary>
        public void ShowPrintReportFormatDialog()
        {
            var report = GetDefaultReport();
            if (report != null)
            {
                report.PrintDialog();
            }
            else
            {
                XtraMessageBox.Show("当前没有选中的报表，无法打印报表！", "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private XtraReport GetDefaultReport()
        {
            if (currReportFormat == null)
                return null;
            RetrieveCurrReportFormat();
            if (currReportFormat.ReportFormat == null || currReportFormat.ReportFormat.Length < 1)
                return null;
            XtraReport result = CreateReport(currReportFormat.ReportFormat, true);
            result.Name = currReportFormat.ReportFormatName;
            result.DisplayName = currReportFormat.ReportFormatName;
            return result;
        }

        private void RetrieveCurrReportFormat()
        {
            if (currReportFormat.ReportFormat != null && currReportFormat.ReportFormat.Length > 0)
                return;
            currReportFormat.ReportFormat = GetReportFormat(currReportFormat.Iden);
        }

        private Form TopLevelForm
        {
            get
            {
                if (this.m_BarSubItem != null)
                {
                    return this.m_BarSubItem.Manager.Form as Form;
                }
                else
                {
                    return this.m_DropDownButton.TopLevelControl as Form;
                }
            }
        }

        private void ShowNewReportFormatDesigner()
        {
            aLastAddFormat = null;
            if (!NewReportForm.NewReport(sysReports, ref aLastAddFormat, TopLevelForm))
            {
                return;
            }
            IsNewReport = true;
            XtraReport report = CreateReport(null, false);
            report.DisplayName = aLastAddFormat.ReportFormatName;
            ShowRibbonDesignerDialog(report);
            report.Dispose();
        }

        private XRDesignRibbonForm ReportDesignerForm
        {
            get
            {
                if (m_ReportDesignerForm == null)
                {
                    m_ReportDesignerForm = new XRDesignRibbonForm();
                }
                return m_ReportDesignerForm;
            }
            set
            {
                m_ReportDesignerForm = value;
            }
        }

        private void ShowRibbonDesignerDialog(XtraReport report)
        {
            ReportDesignerForm.DesignMdiController.SetCommandVisibility(
                new ReportCommand[]{ 
                    ReportCommand.SaveFileAs,
                    ReportCommand.SaveAll,
                    ReportCommand.OpenFile,
                    ReportCommand.NewReport,
                    ReportCommand.NewReportWizard                    
                },
                DevExpress.XtraReports.UserDesigner.CommandVisibility.None);

            //CommandID cmd = new CommandID(new Guid("2b998921-d5c4-4eb9-b4a3-3d72732325d5"), 2);
            foreach (BarItem item in ReportDesignerForm.DesignRibbonController.RibbonControl.Items)
            {
                if ((item is CommandBarItem) && (item as CommandBarItem).Command == ReportCommand.SaveFile)
                {
                    item.ItemClick += new ItemClickEventHandler(SaveBarItem_ItemClick);
                }
            }

            ReportDesignerForm.OpenReport(report);
            ReportDesignerForm.ActiveDesignPanel.FileName = Path.GetTempFileName();

            ReportDesignerForm.ActiveDesignPanel.Report.PrintingSystem.SetCommandVisibility(PrintingSystemCommand.Save, DevExpress.XtraPrinting.CommandVisibility.None);

            var pageGroup = ReportDesignerForm.DesignRibbonController.RibbonControl.GetGroupByName("Document");
            if (pageGroup != null)
            {
                pageGroup.Visible = false;
            }

            ReportDesignerForm.ActiveDesignPanel.ReportStateChanged += new ReportStateEventHandler(ActiveDesignPanel_ReportStateChanged);

            ReportDesignerForm.FormClosing += new FormClosingEventHandler(ReportDesignerForm_FormClosing);

            foreach (XtraMdiTabPage page in ReportDesignerForm.DesignMdiController.XtraTabbedMdiManager.Pages)
            {
                page.ShowCloseButton = DefaultBoolean.False;
            }

            ReportDesignerForm.ShowDialog();
            ReportDesignerForm.Dispose();
            ReportDesignerForm = null;
        }

        void ActiveDesignPanel_ReportStateChanged(object sender, ReportStateEventArgs e)
        {
            if (e.ReportState == ReportState.Changed)
            {
                reportChanged = true;
                (sender as XRDesignPanel).ReportState = ReportState.Saved;
            }
        }

        void ReportDesignerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (reportChanged)
            {
                DialogResult dr = XtraMessageBox.Show("报表已被修改，是否保存？", "确认", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else if (dr == DialogResult.Yes)
                {
                    SaveReportFormat();
                }
            }
        }

        void ReportDesignerForm_Closed(object sender, EventArgs e)
        {
            SaveReportFormat();
        }

        void SaveBarItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            SaveReportFormat();
        }

        public void ShowEditReportForamtDesigner()
        {
            if (currReportFormat == null)
            {
                XtraMessageBox.Show("当前没有选中的报表，无法设计报表！", "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                RetrieveCurrReportFormat();
                if (currReportFormat.ReportFormat == null || currReportFormat.ReportFormat.Length < 1)
                {
                    XtraMessageBox.Show("程序未能获取报表格式，无法设计报表！", "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                aLastAddFormat = currReportFormat;
                IsNewReport = false;
                XtraReport report = CreateReport(currReportFormat.ReportFormat, true);

                ShowRibbonDesignerDialog(report);
                report.Dispose();
            }
        }

        private void SaveReportFormat()
        {
            if (IsNewReport)
            {
                aLastAddFormat.ReportGuid = this.m_ReportGuid;
            }
            else
            {
                aLastAddFormat = currReportFormat;
            }
            System.IO.MemoryStream ms = new MemoryStream();
            ReportDesignerForm.ActiveDesignPanel.Report.SaveLayout(ms);
            byte[] fff = ms.ToArray();
            aLastAddFormat.ReportFormat = fff;

            //保存
            #region 保存报表
            try
            {
                using (SqlConnection con = new SqlConnection(this.m_ConnectionString))
                {
                    con.Open();
                    try
                    {

                        var cmd1 = con.CreateCommand();
                        cmd1.CommandType = CommandType.Text;
                        cmd1.CommandText = string.Format("select count(*) from SysReport with(nolock) where Iden='{0}'", aLastAddFormat.Iden);
                        int count = (int)cmd1.ExecuteScalar();
                        if (count <= 0)
                        {
                            SqlTransaction tran = con.BeginTransaction();
                            try
                            {
                                #region 默认报表时，更新原有默认信息
                                if (aLastAddFormat.IsDefault)
                                {
                                    var cmdDefault = con.CreateCommand();
                                    cmdDefault.Transaction = tran;
                                    cmdDefault.CommandType = CommandType.Text;
                                    cmdDefault.CommandText = string.Format("update SysReport set IsDefault=0 where ReportGuid='{0}'", aLastAddFormat.ReportGuid);
                                    cmdDefault.ExecuteNonQuery();
                                }
                                #endregion

                                #region 新建报表
                                var cmd = con.CreateCommand();
                                cmd.Transaction = tran;
                                cmd.CommandType = CommandType.Text;
                                cmd.CommandText =
                                    "insert SysReport(Iden, ReportGuid, ReportFormatName,ReportFormat,IsDefault,SortIndex,IsActive,Remark) " +
                                    "values(@Iden, @ReportGuid, @ReportFormatName,@ReportFormat,@IsDefault,@SortIndex,@IsActive,@Remark)";
                                SqlParameter param = new SqlParameter("@Iden", SqlDbType.UniqueIdentifier);
                                param.Value = aLastAddFormat.Iden;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@ReportGuid", SqlDbType.UniqueIdentifier);
                                param.Value = aLastAddFormat.ReportGuid;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@ReportFormatName", SqlDbType.NVarChar, 100);
                                param.Value = aLastAddFormat.ReportFormatName;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@ReportFormat", SqlDbType.Image);
                                param.Value = aLastAddFormat.ReportFormat;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@IsDefault", SqlDbType.Bit, 1);
                                param.Value = aLastAddFormat.IsDefault;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@SortIndex", SqlDbType.Int, 4);
                                param.Value = aLastAddFormat.SortIndex;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@IsActive", SqlDbType.Bit, 1);
                                param.Value = aLastAddFormat.IsActive;
                                cmd.Parameters.Add(param);

                                param = new SqlParameter("@Remark", SqlDbType.NVarChar, 200);
                                param.Value = aLastAddFormat.Remark;
                                cmd.Parameters.Add(param);
                                cmd.ExecuteNonQuery();
                                #endregion

                                #region  更新排序
                                foreach (var item in sysReports)
                                {
                                    var cmdSort = con.CreateCommand();
                                    cmdSort.Transaction = tran;
                                    cmdSort.CommandType = CommandType.Text;
                                    cmdSort.CommandText = string.Format("update SysReport set SortIndex={1} where Iden='{0}'", item.Iden, item.SortIndex);
                                    cmdSort.ExecuteNonQuery();
                                }
                                #endregion
                                tran.Commit();
                            }
                            catch
                            {
                                tran.Rollback();
                                throw;
                            }
                        }
                        else
                        {
                            #region 更新报表
                            var cmd2 = con.CreateCommand();
                            cmd2.CommandText = "update SysReport set ReportFormat=@ReportFormat where Iden=@Iden";

                            SqlParameter param = new SqlParameter("@Iden", SqlDbType.UniqueIdentifier);
                            param.Value = aLastAddFormat.Iden;
                            cmd2.Parameters.Add(param);

                            param = new SqlParameter("@ReportFormat", SqlDbType.Image);
                            param.Value = aLastAddFormat.ReportFormat;
                            cmd2.Parameters.Add(param);

                            cmd2.ExecuteNonQuery();
                            #endregion
                        }
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
            catch
            {
                throw;
            }
            #endregion

            //添加报表菜单
            if (IsNewReport)
            {
                AddNewRportBarItemToPopupMenu();
            }

            reportChanged = false;
            IsNewReport = false;
        }

        private void AddNewRportBarItemToPopupMenu()
        {
            BarCheckItem barCheckItem = new BarCheckItem(Manager);
            barCheckItem.Caption = aLastAddFormat.ReportFormatName;
            barCheckItem.Tag = aLastAddFormat;
            barCheckItem.ItemClick += new ItemClickEventHandler(barCheckItem_ItemClick);
            if (aLastAddFormat.IsDefault || sysReports.Count <= 1)
            {
                currReportFormat = aLastAddFormat;
                UnCheckPopupMenuCheckItem();
                barCheckItem.Checked = true;
            }
            if (this.m_DropDownButton != null)
            {
                BarItemLink beforLink = null;
                foreach (LinkPersistInfo linkPersistInfo in this.PopupMenu.LinksPersistInfo)
                {
                    if (linkPersistInfo.Item is BarCheckItem)
                    {
                        BarCheckItem checkItem = (BarCheckItem)linkPersistInfo.Item;
                        var report = checkItem.Tag as sysReport;
                        if (report != null && report.SortIndex == aLastAddFormat.SortIndex + 1)
                        {
                            beforLink = linkPersistInfo.Link;
                            beforLink.BeginGroup = false;
                            break;
                        }
                    }
                }
                BarItemLink itemLink;
                if (beforLink != null)
                {
                    itemLink = PopupMenu.InsertItem(beforLink, barCheckItem);
                }
                else
                {
                    itemLink = PopupMenu.AddItem(barCheckItem);
                }
                if (aLastAddFormat.SortIndex == 1)
                    itemLink.BeginGroup = true;
            }
            if (this.m_BarSubItem != null)
            {
                BarItemLink beforLink = null;
                foreach (LinkPersistInfo linkPersistInfo in this.m_BarSubItem.LinksPersistInfo)
                {
                    if (linkPersistInfo.Item is BarCheckItem)
                    {
                        BarCheckItem checkItem = (BarCheckItem)linkPersistInfo.Item;
                        var report = checkItem.Tag as sysReport;
                        if (report != null && report.SortIndex == aLastAddFormat.SortIndex + 1)
                        {
                            beforLink = linkPersistInfo.Link;
                            beforLink.BeginGroup = false;
                            break;
                        }
                    }
                }
                BarItemLink itemLink;
                if (beforLink != null)
                {
                    itemLink = m_BarSubItem.InsertItem(beforLink, barCheckItem);
                }
                else
                {
                    itemLink = m_BarSubItem.AddItem(barCheckItem);
                }

                if (aLastAddFormat.SortIndex == 1)
                    itemLink.BeginGroup = true;
            }
        }

        private void UnCheckPopupMenuCheckItem()
        {
            if (this.m_DropDownButton != null)
            {
                foreach (LinkPersistInfo linkPersistInfo in this.PopupMenu.LinksPersistInfo)
                {
                    if (linkPersistInfo.Item is BarCheckItem)
                    {
                        BarCheckItem checkItem = (BarCheckItem)linkPersistInfo.Item;
                        checkItem.Checked = false;
                    }
                }
            }
            if (this.m_BarSubItem != null)
            {
                foreach (LinkPersistInfo linkPersistInfo in this.m_BarSubItem.LinksPersistInfo)
                {
                    if (linkPersistInfo.Item is BarCheckItem)
                    {
                        BarCheckItem checkItem = (BarCheckItem)linkPersistInfo.Item;
                        checkItem.Checked = false;
                    }
                }
            }
        }

        private List<Parameter> ReportParameters
        {
            get
            {
                if (reportRarameters == null)
                    reportRarameters = new List<Parameter>();
                return reportRarameters;
            }
        }
        /// <summary>
        /// 为报表设置外置参数
        /// </summary>
        /// <param name="report"></param>
        private void SetReportParameter(XtraReport report)
        {
            foreach (Parameter p in ReportParameters)
            {
                if (report.Parameters.Any(x => x.Name == p.Name))
                {
                    var pp = report.Parameters.First(x => x.Name == p.Name);
                    pp.Value = p.Value;
                    pp.Description = p.Description;
                    pp.Type = p.Type;
                    continue;
                }
                report.Parameters.Add(p);
            }
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="parameterName">名称</param>
        /// <param name="value">值</param>
        public void AddReportParameter(string sParameterName, object value)
        {
            this.AddReportParameter(sParameterName, value, sParameterName);
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="parameterName">名称</param>
        /// <param name="value">值</param>
        /// <param name="parameterDescription">在报表中显示出来的名字</param>
        public void AddReportParameter(string parameterName, object value, string parameterDescription)
        {
            if (string.IsNullOrEmpty(parameterName))
            {
                throw new ArgumentNullException("parameterName");
            }

            if (ReportParameters.Any(x => x.Name == parameterName))
                ReportParameters.First(x => x.Name == parameterName).Value = value;
            else
                ReportParameters.Add(new Parameter() { Name = parameterName, Description = parameterDescription, Value = value, Visible = false });
        }

        private ReportManager()
        {
            components = new System.ComponentModel.Container();
        }

        private ReportManager(DropDownButton dropDownButton, Guid reportGuid, string connectionString)
            : this()
        {
            if (dropDownButton == null)
            {
                throw new ArgumentNullException("dropDownButton");
            }
            if (reportGuid == Guid.Empty)
            {
                throw new ArgumentNullException("reportGuid");
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }
            this.m_DropDownButton = dropDownButton;
            this.m_ReportGuid = reportGuid;
            this.m_ConnectionString = connectionString;
        }

        private ReportManager(BarSubItem barSubItem, Guid reportGuid, string connectionString)
            : this()
        {
            if (barSubItem == null)
            {
                throw new ArgumentNullException("barSubItem");
            }
            if (reportGuid == Guid.Empty)
            {
                throw new ArgumentNullException("reportGuid");
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }
            this.m_BarSubItem = barSubItem;
            this.m_ReportGuid = reportGuid;
            this.m_ConnectionString = connectionString;
        }

        /// <summary>
        /// 绑定报表，DropDownButton Click为预览报表
        /// </summary>
        /// <param name="dropDownButton">要绑定报表的DropDownButton控件</param>
        /// <param name="reportGuid">要绑定的报表Guid</param>
        public static ReportManager BindingReports(DropDownButton dropDownButton, Guid reportGuid, string connectionString)
        {
            var ReportManager = new ReportManager(dropDownButton, reportGuid, connectionString);
            ReportManager.InitPopupMenu();
            return ReportManager;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="barSubItem">要绑定报表的BarSubItem控件</param>
        /// <param name="reportGuid">要绑定的报表Guid</param>
        public static ReportManager BindingReports(BarSubItem barSubItem, Guid reportGuid, string connectionString)
        {
            var ReportManager = new ReportManager(barSubItem, reportGuid, connectionString);
            ReportManager.InitPopupMenu();
            return ReportManager;
        }
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    internal sealed class sysReport
    {
        public Guid Iden { get; set; }
        public Guid ReportGuid { get; set; }
        public string ReportFormatName { get; set; }
        public Byte[] ReportFormat { get; set; }
        public bool IsDefault { get; set; }
        public int SortIndex { get; set; }
        public bool IsActive { get; set; }
        public string Remark { get; set; }

        public sysReport() { }

        public sysReport(IDataReader dataReader)
        {

            this.Iden = new Guid(dataReader["Iden"].ToString());
            this.ReportGuid = new Guid(dataReader["ReportGuid"].ToString());
            this.ReportFormatName = dataReader["ReportFormatName"].ToString();
            //this.ReportFormat = dataReader["ReportFormat"] as byte[];

            object ojb;
            ojb = dataReader["IsDefault"];
            if (ojb != null && ojb != DBNull.Value)
            {
                this.IsDefault = (bool)ojb;
            }
            ojb = dataReader["SortIndex"];
            if (ojb != null && ojb != DBNull.Value)
            {
                this.SortIndex = (int)ojb;
            }
            ojb = dataReader["IsActive"];
            if (ojb != null && ojb != DBNull.Value)
            {
                this.IsActive = (bool)ojb;
            }
            this.Remark = dataReader["Remark"].ToString();
        }
    }

    public sealed class ReportManagerCustomDataSourceEventArgs : EventArgs
    {
        /// <summary>
        /// 报表数据源
        /// </summary>
        public object DataSource
        {
            get;
            set;
        }
        /// <summary>
        /// 报表的GUID
        /// </summary>
        public Guid ReportGuid { get; internal set; }
        /// <summary>
        /// 报表格式名称
        /// </summary>
        public string ReportFormatName { get; internal set; }

    }
}
